package com.atguigu.i_lock_synchronized;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resources{
    public synchronized void sayName(){
        try {
            System.out.println(Thread.currentThread().getName()+"sayHello");
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Lock lock = new ReentrantLock();
    public void sayHi() throws InterruptedException {
        if (lock.tryLock(3,TimeUnit.SECONDS)){
            try
            {
                System.out.println(Thread.currentThread().getName()+"sayHi");
                TimeUnit.SECONDS.sleep(5);
            }finally {
                lock.unlock();
            }
        }else{
            System.out.println("抢锁失败");
        }

    }
}

public class Test {
    public static void main(String[] args){
        // 关于TimeUnit的使用
        try {
            // 暂停五秒
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            // 暂停五毫秒
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Resources resources = new Resources();
        // 使用synchronized
       /* new Thread(new Runnable() {
            @Override
            public void run() {
                resources.sayName();
            }
        },"t1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                resources.sayName();
            }
        },"t2").start();*/

        // 使用lock
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    resources.sayHi();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "a").start();
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    resources.sayHi();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "b").start();
    }
}
